﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkWeiXin.Models;
using Scm.Oms.WebModel;
using Scm.Oms.TBL;
using Scm.Oms.SSBL;
using Scm.Component.SecurityModel;
using Scm.Oms.FIBL;
using Scm.Oms.PMBL;
using System.IO;
using DingTalk.Models;

namespace Scm.Oms.Service
{
    public class DingTalkOAService
    {
        private OAUser _user;
        public DingTalkOAService(OAUser user) 
        {
            _user = user;
        }
        /// <summary>
        /// 发起销售合同审批
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public void SendSalesConractApply(decimal id,decimal menuId)
        {
            SalesContractWebModel model = new SalesContractBL().Get(id).AsWebModel();
            ApiObjectEntity apiObject = new ApiObjectBL().GetByChNameAndMenuID("销售合同审批", menuId).First(m => m.OAType == OAType.DingTalk);
            if (apiObject != null && !string.IsNullOrWhiteSpace(apiObject.TemlpateID))
            {
                QYWeiXinApiService qyWeiXinApi = QYWeiXinApiService.GetInstance();
                if (string.IsNullOrWhiteSpace(this._user.MobileNo))
                {
                    throw new Exception(string.Format("用户{0}未设置手机号", this._user.UserName));
                }
                string userId = qyWeiXinApi.GetUserIdByMobile(this._user.MobileNo);
                //C4UFsmGLzGFeEbtRxWkunZWCGxXi8TDsJsiCsj6y1 销售合同审批
                string saleContractTemplate = apiObject.TemlpateID;
                TemplateDetailModel templateModel = qyWeiXinApi.GetTemplateDetail(saleContractTemplate);
                #region 上传临时素材
                string report = CurrentSysSetting.SysSetting.BaseReportUrl + "/" + apiObject.ReportUrl;
                var url = string.Format(CurrentSysSetting.SysSetting.ReportUrl + "{0}&id={1}&format=pdf&extype=ori", report, id);
                string fileName = String.Format("{0}.pdf", apiObject.ReportTitle);
                string fileId = qyWeiXinApi.HttpUploadFile("file", id.ToString(), fileName, url);
                if (fileId == "42001")
                {
                    qyWeiXinApi.GetAccessToken();
                    fileId = qyWeiXinApi.HttpUploadFile("file", id.ToString(), fileName, url); ;
                }
                List<FileValue> billAttachList = this.GetBillAttachList(id, qyWeiXinApi);
                billAttachList.Add(new FileValue
                {
                    file_type = "file",
                    file_id = fileId
                });
                #endregion
                string requestContent = "";
                string spNo = qyWeiXinApi.CreatSaleContactApply(userId, saleContractTemplate, templateModel, model, billAttachList, out requestContent);
                if (!string.IsNullOrWhiteSpace(spNo))
                {
                    ApiLogWebModel logModel = new ApiLogWebModel();
                    logModel.SerialNo = spNo;
                    logModel.Status = Scm.Component.Common.CommonMDStatus.Enable;
                    logModel.Name = apiObject.Name;
                    logModel.Parameter = "";
                    logModel.ApiObjectID = apiObject.ID;
                    logModel.DataID = model.ID;
                    logModel.Bill = model.BillNo;
                    logModel.TimeStamp = DateTime.Now;
                    logModel.IsSucceedType = IsSucceedType.Succeed;
                    logModel.RequestContent = "";//返回内容过长，暂不存储
                    new ApiLogBL().Save(this.AsApiLogEntity(logModel),false);
                }
            }
        }

        /// <summary>
        /// 发起采购付款申请审批
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public void SendPurchasePayApply(decimal id, decimal menuId)
        {
            PayApplyWebModel model = new PayApplyBL().Get(id).AsWebModel();
            ApiObjectEntity apiObject = new ApiObjectBL().GetByChNameAndMenuID("采购付款申请", menuId).First(m => m.OAType == OAType.DingTalk);
            if (apiObject != null && !string.IsNullOrWhiteSpace(apiObject.TemlpateID))
            {
                DingTalkApi dingTalkApi = DingTalkApi.GetInstance();
                if (string.IsNullOrWhiteSpace(this._user.MobileNo))
                {
                    throw new Exception(string.Format("用户{0}未设置手机号", this._user.UserName));
                }
                string userId = dingTalkApi.GetUserIDByMobile(this._user.MobileNo);
                if (string.IsNullOrWhiteSpace(userId))
                {
                    throw new Exception(string.Format("用户{0}获取钉钉用户ID失败", this._user.UserName));
                }
                //获取用户详情
                var userInfo = dingTalkApi.GetUserInfoByUserID(userId);
                if (userInfo == null)
                {
                   throw new Exception(string.Format("用户{0}获取钉钉用户详情失败", this._user.UserName)); 
                }
                //获取钉盘空间ID
                string spaceId = dingTalkApi.GetAttachSpaceID(userId);
                if (string.IsNullOrWhiteSpace(spaceId))
                {
                    throw new Exception(string.Format("用户{0}获取钉盘空间失败", this._user.UserName));
                }
                //创建文件夹获取UUID
                string uuId = dingTalkApi.CreateFolder(userInfo.unionid, spaceId, userId);
                if (string.IsNullOrWhiteSpace(uuId))
                {
                    throw new Exception(string.Format("用户{0}创建文件夹失败", this._user.UserName));
                }
                #region 上传临时素材
                string report = CurrentSysSetting.SysSetting.BaseReportUrl + "/" + apiObject.ReportUrl;
                var url = string.Format(CurrentSysSetting.SysSetting.ReportUrl + "{0}&ids={1}&format=pdf&extype=ori", report, id);
                string fileName = String.Format("{0}.pdf", apiObject.ReportTitle);
                List<DingFileInfoModel> dingFileInfos = new List<DingFileInfoModel>();
                //文件夹授权
                bool auth = dingTalkApi.AddFolderPermission(uuId, userInfo.unionid, userId);
                if (auth)
                {
                    var uploadInfo = dingTalkApi.GetFileUploadInfo(userInfo.unionid, spaceId, uuId);
                    //上传文件
                    var upRes = DingTalkApi.HttpRequest(uploadInfo.headerSignatureInfo.resourceUrls[0], url, uploadInfo.headerSignatureInfo.headers);
                    DingFileInfoModel dingFileInfo = dingTalkApi.commitFile(uuId, userInfo.unionid, uploadInfo.uploadKey, fileName);
                    dingFileInfos.Add(dingFileInfo);
                }
                #endregion
                string payApplyTemplateId = apiObject.TemlpateID;
                //获取审批表单结构
                var formComponents = dingTalkApi.QuerySchemaByProcessCode(payApplyTemplateId);
                //发起审批
                string spNo = dingTalkApi.CreatePayApplyProcess(userInfo, payApplyTemplateId, formComponents, dingFileInfos, model);
                if (!string.IsNullOrWhiteSpace(spNo))
                {
                    ApiLogWebModel logModel = new ApiLogWebModel();
                    logModel.SerialNo = spNo;
                    logModel.Status = Scm.Component.Common.CommonMDStatus.Enable;
                    logModel.Name = apiObject.Name;
                    logModel.Parameter = "";
                    logModel.ApiObjectID = apiObject.ID;
                    logModel.DataID = model.ID;
                    logModel.Bill = model.BillNo;
                    logModel.TimeStamp = DateTime.Now;
                    logModel.IsSucceedType = IsSucceedType.Succeed;
                    logModel.RequestContent = "";//返回内容过长，暂不存储
                    new ApiLogBL().Save(this.AsApiLogEntity(logModel), false);
                }
            }
        }
        /// <summary>
        /// 发起采购合同审批
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public void SendPurchaseContractApply(decimal id, decimal menuId)
        {
            PurchaseContractWebModel model = new PurchaseContractBL().Get(id).AsWebModel();
            ApiObjectEntity apiObject = new ApiObjectBL().GetByChNameAndMenuID("采购合同审批", menuId).First(m => m.OAType == OAType.DingTalk);
            if (apiObject != null && !string.IsNullOrWhiteSpace(apiObject.TemlpateID))
            {
                QYWeiXinApiService qyWeiXinApi = QYWeiXinApiService.GetInstance();
                if (string.IsNullOrWhiteSpace(this._user.MobileNo))
                {
                    throw new Exception(string.Format("用户{0}未设置手机号", this._user.UserName));
                }
                string userId = qyWeiXinApi.GetUserIdByMobile(this._user.MobileNo);
                //C4UFsmGLzGFeEbtRxWkunZWCGxXi8TDsJsiCsj6y1 销售合同审批
                string payApplyTemplateId = apiObject.TemlpateID;
                TemplateDetailModel templateModel = qyWeiXinApi.GetTemplateDetail(payApplyTemplateId);
                #region 上传临时素材
                string report = CurrentSysSetting.SysSetting.BaseReportUrl + "/"+apiObject.ReportUrl;
                var url = string.Format(CurrentSysSetting.SysSetting.ReportUrl + "{0}&id={1}&format=pdf&extype=ori", report, id);
                string fileName = String.Format("{0}.pdf", apiObject.ReportTitle);
                string fileId = qyWeiXinApi.HttpUploadFile("file", id.ToString(), fileName, url);
                if (fileId == "42001")
                {
                    qyWeiXinApi.GetAccessToken();
                    fileId = qyWeiXinApi.HttpUploadFile("file", id.ToString(), fileName, url); ;
                }
                List<FileValue> billAttachList = this.GetBillAttachList(id, qyWeiXinApi);
                billAttachList.Add(new FileValue
                {
                    file_type = "file",
                    file_id = fileId
                });
                #endregion
                string requestContent = "";
                string spNo = qyWeiXinApi.CreatPurchaseContactApply(userId, payApplyTemplateId, templateModel, model, billAttachList, out requestContent);
                if (!string.IsNullOrWhiteSpace(spNo))
                {
                    ApiLogWebModel logModel = new ApiLogWebModel();
                    logModel.SerialNo = spNo;
                    logModel.Status = Scm.Component.Common.CommonMDStatus.Enable;
                    logModel.Name = apiObject.Name;
                    logModel.Parameter = "";
                    logModel.ApiObjectID = apiObject.ID;
                    logModel.DataID = model.ID;
                    logModel.Bill = model.BillNo;
                    logModel.TimeStamp = DateTime.Now;
                    logModel.IsSucceedType = IsSucceedType.Succeed;
                    logModel.RequestContent = "";//返回内容过长，暂不存储
                    new ApiLogBL().Save(this.AsApiLogEntity(logModel), false);
                }
            }
        }
        /// <summary>
        /// 根据单据ID获取附件列表
        /// </summary>
        /// <param name="billId"></param>
        /// <param name="qyWeiXinApi"></param>
        /// <param name="uuId"></param>
        /// <param name="userInfo"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        private List<FileValue> GetBillAttachList(decimal billId, QYWeiXinApiService qyWeiXinApi,string uuId,DingUserInfoModel userInfo, string userId)
        {
            List<FileValue> attachs = new List<FileValue>();
            //获取8个附件
            List<FileAddressEntity> attachList = new FileAddressBL().GetListByBillId(billId).Take(8).ToList();
            if (attachList.Any())
            {
                attachList.ForEach(attach =>
                {
                    if (!string.IsNullOrWhiteSpace(attach.FileAddress))
                    {
                        FileInfo fileInfo = new FileInfo(attach.FileAddress);
                        if (fileInfo.Exists)
                        {
                            string fileEx = fileInfo.Extension.ToLower().Replace(".", "");
                            string imageEx = "jpg、jpeg、png、gif";
                            string fileType = imageEx.Contains(fileEx) ? "image" : "file";
                            string fileId = qyWeiXinApi.HttpUploadFile("file", billId.ToString(), attach.FileName, attach.FileAddress, 2);
                            if (fileId=="42001")
                            {
                                qyWeiXinApi.GetAccessToken();
                                fileId = qyWeiXinApi.HttpUploadFile("file", billId.ToString(), attach.FileName, attach.FileAddress, 2);
                            }
                            attachs.Add(new FileValue
                            {
                                file_type = fileType,
                                file_id = fileId
                            });
                        }
                    }
                });
            }
            return attachs;
        }
        /// <summary>
        /// 由于队列无法读取当前用户，不能直接调用webmodel里面的扩展方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private ApiLogEntity AsApiLogEntity(ApiLogWebModel model) 
        {
            Scm.Component.Common.DataProcess.InitModel(model);

            ApiLogEntity entity = new ApiLogEntity();
            entity.ID = JG.Core.IdGenerator.Next();
            entity.CreateUserID = this._user.UserID;
            entity.CreateDate = Scm.Component.Common.DateTimeUtil.GetNowDateTime();
            entity.UpdateUserID = this._user.UserID;
            entity.UpdateDate = Scm.Component.Common.DateTimeUtil.GetNowDateTime();
            entity.ClientID = this._user.UserClientID;
            entity.OrgID = this._user.UserOrgID;
            entity.StaffID = this._user.UserStaffID;
            entity.Status = Scm.Component.Common.CommonMDStatus.Enable;
            entity.Name = string.Empty;
            entity.Parameter = string.Empty;
            entity.Error = string.Empty;
            entity.Name = model.Name;
            entity.Parameter = model.Parameter;
            entity.Error = model.Error;
            entity.ApiObjectID = model.ApiObjectID.Value;
            entity.DataID = model.DataID.Value;
            entity.Bill = model.Bill;
            entity.TimeStamp = model.TimeStamp.Value;
            entity.IsSucceedType = model.IsSucceedType.Value;
            entity.DataStatus = model.DataStatus.Value;
            entity.SerialNo = model.SerialNo;
            entity.RequestContent = model.RequestContent;
            entity.ResponseContent = model.ResponseContent;
            return entity;
        }
    }
}
